const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const koaBody = require('koa-body');
const cors = require('koa2-cors');
const path = require('path')
const static = require('koa-static')


require("./dao/database.js")
const index = require('./routes/index')
const users = require('./routes/users')
const cars = require("./routes/cars")
const orders = require("./routes/orders")

// error handler
onerror(app)

app.use(cors({
  credentials: true,
  // origin: 'http://127.0.0.1:3001'
}));

app.use(static(
    path.join(__dirname,"./img")
));

app.use(koaBody({
    multipart: true,
    formidable: {
        // uploadDir:path.join(__dirname, 'img/'),
        maxFileSize: 200*1024*1024, // 设置上传文件大小最大限制，默认2M
        keepExtensions: true,
        onFileBegin:(name ,file) => {

            file.path = "img/"+ file.name;
        }
    }
}));
// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
// app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
app.use(async (ctx,next)=>{
  console.log(1);
  ctx.set("Access-Control-Allow-Origin","*");
  await next();
});

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(cars.routes(), cars.allowedMethods())
app.use(orders.routes(), orders.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

// module.exports = app
app.listen('3000', function() {
  console.log("http://localhost:3000/ 启动成功！");
})
